package cn.bdqn.tangcco.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;

import javax.inject.Inject;
import java.beans.PropertyVetoException;
import java.util.Properties;

/**
 * Created by Administrator on 2016/6/2.
 */
@Configuration
@PropertySource(value = {"classpath:jdbc.properties"})
public class HibernateConfig {

    @Inject
    private Environment environment;

    @Bean
    public ComboPooledDataSource getDatasource(){
        ComboPooledDataSource dataSource = new ComboPooledDataSource();

        try {
            dataSource.setDriverClass(this.environment.getRequiredProperty("jdbc.driver"));
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        dataSource.setJdbcUrl(this.environment.getRequiredProperty("jdbc.url"));
        dataSource.setUser(this.environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(this.environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactoryBean(){
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();

        sessionFactoryBean.setDataSource(this.getDatasource());
        sessionFactoryBean.setHibernateProperties(this.getProperties());
        sessionFactoryBean.setPackagesToScan("cn.bdqn.tangcco.entity");
        return sessionFactoryBean;

    }

    @Bean
    public HibernateTransactionManager transactionManager(){
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();

        transactionManager.setSessionFactory(this.sessionFactoryBean().getObject());

        return transactionManager;
    }





    private Properties getProperties(){
        Properties properties = new Properties();

        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.format_sql", "true");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
        return properties;
    }

















}
